package com.pxst.fi.utils;

import java.util.Base64;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.pxst.exception.DecryptException;

/** 
* @author yangxy
* @version 创建时间：2023年9月6日 上午11:59:08 
*/
public class AESUtil {

    /**
     * 加密
    * @author yangxy
    * @version 创建时间：2023年9月6日 下午5:46:46 
    * @param sSrc 待加密内容
    * @param sKey 秘钥
    * @param ivParameter 偏移量
    * @return
    * @throws Exception
     */
    public static String encrypt(String sSrc, String sKey, String ivParameter) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = Base64.getDecoder().decode(sKey);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(ivParameter));//使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(encrypted);
//        return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
    }

    /**
     * 解密
    * @author yangxy
    * @version 创建时间：2023年9月6日 下午2:07:31 
    * @param sSrc 密文
    * @param sKey 秘钥
    * @param ivParameter 偏移量
    * @return
    * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey, String ivParameter) throws Exception {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(sKey), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(ivParameter));
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] decodeBase64 = org.apache.commons.codec.binary.Base64.decodeBase64(sSrc);
            byte[] original = cipher.doFinal(decodeBase64);
            String originalString = new String(original);
            return originalString;
        } catch (Exception ex) {
        	ex.printStackTrace();
            return null;
        }
    }
    
    /**
     * 解密
    * @author yangxy
    * @version 创建时间：2023年9月6日 下午2:07:31 
    * @param crypt 密文
    * @param sKey 秘钥
    * @return
    * @throws Exception
     */
    public static String decrypt(String crypt, String sKey) {
        try {
        	String decoded1 = new String(Base64.getDecoder().decode(crypt));
        	JSONObject json = JSON.parseObject(decoded1);
            SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(sKey), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(json.getString("iv")));
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] decodeBase64 = org.apache.commons.codec.binary.Base64.decodeBase64(json.getString("value"));
            byte[] original = cipher.doFinal(decodeBase64);
            String originalString = new String(original);
            return originalString;
        } catch (Exception ex) {
        	ex.printStackTrace();
        	throw new DecryptException("The payload is invalid");
        }
    }
    /**
     * 生成秘钥或偏移量
    * @author yangxy
    * @version 创建时间：2023年9月6日 下午5:47:20 
    * @return
     */
    public static String getRandom(){
        char[] arr = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k',
                'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        String result = String.valueOf(arr[(int)Math.floor(Math.random()*36)]);
        for(int i = 1;i<16;i++){
            result+=arr[(int)Math.floor(Math.random()*36)];
        }
        return Base64.getEncoder().encodeToString(result.getBytes());
    }
    
    public static void main(String[] args) throws Exception {
//    	String ss1 = AESUtil.decrypt(encrypt, 
//    			"WKOBlNUlzvNzh9g/9uBfqQ==", 
//    			"2u2Ldqx19SrgAXSQr24Lcw==");
//    	System.out.println(ss1);
    	Base64.Decoder decoder = Base64.getDecoder();
		String decoded = new String(decoder.decode("eyJpdiI6IlZtMlNLYUxPbjkrQmp1c05iTnk4S3c9PSIsInZhbHVlIjoiNU1zeHZKTDZ3NENlRlBkWXkrSTVMSGFRVVwvS2dYVDkwVmFhMGQrMnJnTVwvWFJ5NjhQREVCQVNucWMzME1ReHlXcTBpNmFMZ2tXa1AxdWNxUHNcL0JPaCtRQkJSb002dW1tVXk0cTg5S09SVmFoYXYzbFQzTFpTTEtuRE9nUUw0RXY1RG1YemxxVytOdVkwKzFSb2djK2NXZURmZFAwZU9zRmsrWThLSXU0NE9UelwvQjltM2x3OTZcL3h4RHNqRWRuOERveW1vdkZib2ZMSVRreGRjbUZtM3dVK0dOYjl6WXI0TlJLSVg4QjJqVGlpOFcxWVdNYUpqcjAxdjdTdFljNHB2U2dMeWM4aTdpN2k3emlxUnRybUlqZ0ttbmpkTjJBam5yNENCcjhmeW9IWT0ifQ=="));
		
		JSONObject parseObject = JSON.parseObject(decoded);
		String ss = AESUtil.decrypt(parseObject.getString("value"), 
    			"DXBPqxm9oXdk1jwCd+jfzg==", 
    			"Vm2SKaLOn9+BjusNbNy8Kw==");
    	System.out.println(ss);
    	
    	String encrypt2 = AESUtil.encrypt(ss,"DXBPqxm9oXdk1jwCd+jfzg==", 
    			"Vm2SKaLOn9+BjusNbNy8Kw==");
    	Map<String,String> map = Maps.newHashMap();
    	map.put("iv", "Vm2SKaLOn9+BjusNbNy8Kw==");
    	map.put("value", encrypt2);
    	String jsonString = JSON.toJSONString(map);
    	String encodeToString = Base64.getEncoder().encodeToString(jsonString.getBytes());
    	String decoded1 = new String(decoder.decode(encodeToString));
    	JSONObject parseObject1 = JSON.parseObject(decoded1);
    	String ss1 = AESUtil.decrypt(parseObject1.getString("value"), 
    			"DXBPqxm9oXdk1jwCd+jfzg==", 
    			"Vm2SKaLOn9+BjusNbNy8Kw==");
    	System.out.println(ss1);
    	String ss3 = AESUtil.decrypt("eyJpdiI6IlRcL2Y4aTU0ZTdCM3VFM3FyTTQxc2NBPT0iLCJ2YWx1ZSI6IkJodmhTbEFETXdFQXRtcnhVMDBXWHpleU9QYzZaaWY4K2dZeWZUOEhtMGlaRkJVMU1sMHN0WWF5R3p4ZmhYS2lBTFVMZGZGRUFYU0hveFpUS1g4Q01Ec3F0U1ZBbStmRXhETmdNUUhWXC9sWVFsUmJEUHRlNUZXa055MTF4WG9aZUdmU01mOGpSSFwvWnBhVXZzd1VPVlwvV3o5TEpsSTBzMHQzUjdxZjU2cG1wWUVwblhEd290SWh1UTJ1TURSNkswRFFhSmJ5bHJVeExjZ0ZBMUo0VHBVdU5DVUQwbnFLXC80Z1NVN1ZSRGVTS1l6WUVTQ0taRStyUDVrcTQxZFExQXhBVVNJdlwveXI3UExhbXR4d0d2andnSHBWVVd0VUNcL1wvdmFJWFJVUWExMXNlYz0ifQ==", 
    			"DXBPqxm9oXdk1jwCd+jfzg==");
    	System.out.println(ss3);
    }
}
